﻿using System;
using System.IO;
using System.Threading.Tasks;
using Kiwi.Node;

namespace kn
{
    class Program
    {
        static void Main(string[] args)
        {
            Directory.SetCurrentDirectory("..\\..");

            var fileSystemWatcher = new FileSystemWatcher()
                                        {
                                            Filter = "*.*",
                                            Path = Environment.CurrentDirectory,
                                            IncludeSubdirectories = true
                                        };

            var restart = false;
            Action<string> fileSystemChange = path =>
                                                  {
                                                      if (!restart)
                                                      {
                                                          Console.Out.WriteLine(
                                                              "[System] Detected change in {0} - reinitialization pending",
                                                              path);
                                                          restart = true;
                                                      }
                                                  };
            fileSystemWatcher.Changed += (o, a) => fileSystemChange(a.FullPath);
            fileSystemWatcher.Deleted += (o, a) => fileSystemChange(a.FullPath);
            fileSystemWatcher.Renamed += (o, a) => fileSystemChange(a.FullPath);
            fileSystemWatcher.EnableRaisingEvents = true;

            var quit = false;
            Task.Factory.StartNew(() =>
            {
                Console.Out.WriteLine("Press enter to exit...");
                Console.ReadLine();
                quit = true;
            }, TaskCreationOptions.LongRunning);
            while (!quit)
            {
                var app = new Application();
                app.Resolve("main.js");
                app.Events.RunEventLoop(() => !(restart || quit));
                if (!restart)
                {
                    quit = true;
                }
                //quit = quit || !app.Events.RunEventLoop(() => !(restart || quit));
                restart = false;
            }
        }
    }
}
